package com.ceba.test.modules.signvisual.logicService.custom;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ceba.base.sign.enums.ErrSign;
import com.ceba.base.utils.IDSFileUtils;
import com.ceba.base.utils.ToPdfUtils;
import com.ceba.base.web.response.ResultJson;
import com.ceba.test.base.config.LogicPathUtil;
import com.ceba.test.base.constants.CustomStampConstants;
import com.ceba.test.modules.signvisual.logicService.SignVisualAbstractOperate;
import com.ceba.test.modules.storage.logicService.StorageFileCacheManage;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.ceba.test.base.configs.CebaPathUtil;
import com.ceba.test.base.entity.PdfImage;
import com.ceba.test.base.entity.SignPrintPDF;
import com.ceba.test.base.enums.ImageFormatEnum;
import com.ceba.test.base.enums.ResultStatusEnum;
import com.ceba.test.base.sign.helper.CheckSignHelper;
import com.ceba.test.modules.admin.entity.GStamp;
import com.ceba.test.modules.admin.helper.GStampHelper;
import com.ceba.test.modules.filemanage.logicService.FileManageLogicService;
import com.ceba.test.modules.signvisual.enums.SignVisualAbstractEnum;
import com.ceba.test.modules.statistic.entity.ReportSign;

import abc.ID;
import configs.context.SpringBeans;


public class CustomStampSignVisualLogicService{
	private Logger logger = LoggerFactory.getLogger(CustomStampSignVisualLogicService.class);
	
	private FileManageLogicService fileManageLogicService =
				SpringBeans.getFileManageLogicService("fileManageLogicService");
	
	/**
	 * 取得文件的正式路径
	 * @param fileId
	 * @param isTemplates
	 * @return
	 */
	public String getFilePath(String fileId,String isTemplates){
		Map<String,String> resultMap = fileManageLogicService.getPdfPath(fileId,isTemplates);
 		return resultMap.get("filePath");
	}
	/**
	 * 获取pdf图片
	 * @param pdfPath
	 * @return
	 */
	public Map<String, Object> getPdfImageList(String pdfPath){
		Map<String, Object> resultMap=new HashMap<>();
		List<PdfImage> pdfImageList=new ArrayList<>();
		resultMap.put("pdfImageList", pdfImageList);
		//1.创建储存图片的文件夹
		String pdfImageDir="pdfImage"+new Date().getTime()+File.separator;
		String imagePath= LogicPathUtil.getPhysicalTempFolder(StorageFileCacheManage.getSystemUseAddressId())+pdfImageDir;
		IDSFileUtils.createDir(imagePath);
		String tempFilePath=null;
		//2.生成PDF图片
		String imageFormat=ImageFormatEnum.JPG.getImageFormat();
		if(!pdfPath.endsWith(".pdf")){
			tempFilePath= LogicPathUtil.getPhysicalTempFolder(StorageFileCacheManage.getSystemUseAddressId())+"out"+File.separator+ID.getGuid()+".pdf";
			ToPdfUtils.fileToPdf(pdfPath, tempFilePath);
		}else{
			tempFilePath=pdfPath;
		}
		ToPdfUtils.pdfToPic(new File(tempFilePath).getPath(),imagePath,ToPdfUtils.SCALE,imageFormat);
		Map<Integer, PdfImage> pdfImageMap=new HashMap<>();
		//3.获取所有PDF图片
		File[] files=new File(imagePath).listFiles();
		for(int i=0;i<files.length;i++){
			File file=files[i];
			String path= CebaPathUtil.getProjectContextPath()+CebaPathUtil.getVirtualTempPath()+pdfImageDir+file.getName();
			String page=file.getName().replace("."+imageFormat, "");
			String pdfName=new File(pdfPath).getName();
			PdfImage pdfImage=new PdfImage();
			pdfImage.setFileName(pdfName);
			pdfImage.setPage(page);
			pdfImage.setZoom(true);
			pdfImage.setZoomRate(ToPdfUtils.SCALE+"");
			pdfImage.setImagePath(path);
			Integer key=NumberUtils.toInt(file.getName().replace("."+imageFormat, ""));
			pdfImageMap.put(key, pdfImage);
		}
		Integer mIn=-1;
		for(Integer key:pdfImageMap.keySet()){
			Integer test=key;
			for(Integer keya:pdfImageMap.keySet()){
				if(test > keya && keya > mIn){
					test=keya;
				}
			}
			mIn=test;
			pdfImageList.add(pdfImageMap.get(test));
		}
		resultMap.put("tempFilePath", tempFilePath);
		return resultMap;
	}
	/**
	 * 获取签章
	 * @return
	 */
	public List<GStamp> getG_StampList(Map<String, Object> paramMap){
		List<GStamp> g_StampList=null;
		try {
			g_StampList = GStampHelper.getCustomStampsListByIds(paramMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return g_StampList;
	}
	/**
	 * 签章打印PDF操作
	 * @param pdfPath
	 * @return
	 */
	public ResultJson signPrintPDFseal(List<SignPrintPDF> signPrintPDFList, String pdfPath){
		ResultJson resultJson=new ResultJson();
		SignVisualAbstractOperate signVisualAbstractOperate=new SignVisualAbstractOperate(SignVisualAbstractEnum.ONESIGN);
		String signData=JSON.toJSONString(signPrintPDFList);
		try {
			logger.debug("签名文件路径："+pdfPath+"签章位置数据："+signData);
			String outPath=signVisualAbstractOperate.seal(signPrintPDFList, pdfPath,null);
			if(StringUtils.isNotBlank(outPath)){
				resultJson.setStatus(ResultStatusEnum.CG.getCode());
				Map<String, String> map=new HashMap<>();
//				String relativePath= CebaPathUtil.getProjectContextPath()+CebaPathUtil.getVirtualUpfilePath()+outPath.replace(CebaPathUtil.getPhysicalWebUploadPath(), "");
				String relativePath= LogicPathUtil.getVirtualPath(StorageFileCacheManage.getSystemUseAddressId(),outPath);
				map.put("relativePath", relativePath);
				map.put("path", outPath);
				resultJson.setData(map);
				logger.debug("签章文件路径："+pdfPath+"签章位置数据："+signData+"输出文件"+outPath+"签章成功");
			}else{
				resultJson.setStatus(ResultStatusEnum.SB.getCode());
				resultJson.setData(null);
				logger.debug("签章文件路径："+pdfPath+"签章位置数据："+signData+"签章失败");
			}
		} catch (Exception e) {
			resultJson.setStatus(ResultStatusEnum.SB.getCode());
			resultJson.setMessage(e.getMessage());
			logger.debug("签章文件路径："+pdfPath+"签章位置数据："+signData+"签章失败：原因："+e.getMessage());
			resultJson.setData(null);
			e.printStackTrace();
		}
		return resultJson;
	}

	/**
	 * 加载PDF和签章
	 * @param g_stempIds 签章ID 字符串 用 逗号隔开
	 * @param fileId 文件ID
	 * @param isTemplates 是否是模板文件，还是报告文件
	 * @return
	 */
	public String loadPDFandSign(String g_stempIds,String fileId,String isTemplates){
		logger.debug("g_stempIds:"+g_stempIds+"fileId:"+fileId+"是否是模板文件isTemplates:"+isTemplates);
		Map<String,String> fileMap= fileManageLogicService.getPdfPath(fileId,isTemplates);
		String pdfPath=fileMap.get("filePath");
 		Map<String,Object> resultMap=getPdfImageList(pdfPath);
		Map<String, Object> paramMap=new HashMap<>();
		paramMap.put("g_stempIds", g_stempIds);
		List<GStamp> g_StampList=getG_StampList(paramMap);
		Map<String, Object> map=new HashMap<String,Object>();
		map.put(CustomStampConstants.PDFIMAGELIST, (List<PdfImage>)resultMap.get("pdfImageList"));
		map.put(CustomStampConstants.G_STAMPLIST, g_StampList);
		//TODO 根据实际情况而定
		map.put(CustomStampConstants.PDFNAME,fileMap.get("fileName"));
		String fileName=fileMap.get("fileName");
		String result=null;
		if(StringUtils.isNotBlank(fileName) &&  fileName.length()>15){
			result=fileName.substring(0, 15)+"...";
		}
		map.put("pdfNameStr", result);
		map.put("fileId",fileMap.get("fileId"));
		map.put("signFilePath", ObjectUtils.toString(resultMap.get("tempFilePath")));
		map.put("isTemplates", isTemplates);
		String outString=JSON.toJSONString(map);
		logger.debug(outString);
		return outString;
	}
	/**
	 * PDF打印签章
	 * @return
	 */
	public String pdfPrintSign(List<SignPrintPDF> signPrintPDFList,String signFilePath){
		ResultJson resultJson=signPrintPDFseal(signPrintPDFList,signFilePath);
		return JSON.toJSONString(resultJson);
	}

	
}
